import 'dart:async';

/// 运行
main() async {
  // 获取计数
  var stream = countStream(10);
  // 计算和
  var sum = await sumStream(stream);
  print(sum);
}

/// 创建流
/// @return async* 返回一个 Iterable
Stream<int> countStream(int num) async* {
  for (int i = 0; i <= num; i++) {
    if (i == 4) {
      // 抛出异常
      throw Exception('Intentional Exception');
    }
    yield i;
  }
}

/// 计算和
Future<int> sumStream(Stream<int> stream) async {
  var sum = 0;
  // 捕获异常
  try {
    // 累加
    await for (var value in stream) {
      sum += value;
    }
  } catch (e) {
    return -1;
  }
  return sum;
}